package cn.cloud9.opencloud.common.spring.advice;

import cn.cloud9.opencloud.common.api.Result;
import cn.cloud9.opencloud.common.api.ResultMessage;
import cn.cloud9.opencloud.common.exception.ServiceException;
import cn.cloud9.opencloud.common.util.EmptyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author OnCloud9
 * @description
 * @project Open-Cloud
 * @date 2022年04月16日 14:41
 */
@RestControllerAdvice(annotations = {RestController.class})
public class ExceptionAdvice {
    private Logger _logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 对服务异常的设置
     * @param serviceException
     * @return
     */
    @ExceptionHandler(value = {ServiceException.class})
    public Result<String> badRequestWithServiceException(ServiceException serviceException) {
        _logger.error(serviceException.getMessage(), serviceException);

        final Object[] arguments = serviceException.getArguments();
        final ResultMessage resultMessage = serviceException.getResultMessage();
        final Result<String> result = Result.getInstance();

        // 判断是否说明了异常参数
        if (EmptyUtil.isEmptyArray(arguments)) return result.error(resultMessage);
        return result.error(resultMessage, arguments);
    }

    /**
     * 普通异常就直接打印错误信息，直接报系统异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    public Result<String> badRequestWithException(Exception exception) {
        _logger.error(exception.getMessage(), exception);
        final Result<String> result = Result.getInstance();
        return result.error(ResultMessage.SYSTEM_ERROR);
    }
}
